<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>初始结构搭建</title>
  <script src="./MyPromise.js"></script>
</head>
<body>
  <script>
    let p = new MyPromise((resolve, reject) => {
      resolve('OK')
      // reject('NO')
      // throw 'error'
      // setTimeout(() => {
      //   resolve('okkk')
      //   // reject('nooo')
      // },3000)
    })
    console.log('Promise对象', p);
    // const result = p.then(
    //   // (value) => {console.log(value)},
    //   // 回调函数的返回值是PromiseResult
    //   (value) => {
    //     return value
    //   },
    //   // (value) => {
    //   //   return new Promise((resolve, reject) => {
    //   //     // resolve('success')
    //   //     // reject('fail')
    //   //     throw 'fail'
    //   //   })
    //   // },
    //   // (reason) => {console.log(reason)}
    //   (reason) => {
    //     return reason
    //     // throw 'ERROR'
    //   }
    // )
    // console.log('then的返回值',result);
    // p.then(
    //   (value) => {alert(value)},
    //   (reason) => {alert(reason);}
    // )

    // const res = p.catch(reason => {
    //   console.warn(reason)
    // })
    // console.log(res);

    // 异常穿透
    // p.then()
    // .then(value => {
    //   console.log(111);
    //   throw 'ERROR'
    // }).then(value => {
    //   console.log(222);
    // }).then(value => {
    //   console.log(333);
    // }).catch(reason => {
    //   console.warn(reason);
    // })

    // 不传参数
    p.then()
    .then(value => {
      console.log(222);
    }).then(value => {
      console.log(333);
    })

    const p2 = MyPromise.resolve('OK')
    console.log('p2', p2);

    const p3 = MyPromise.resolve(
      new MyPromise(
        (resolve, reject) =>
        resolve('success')
        // reject('fail')
      )
    )
    console.log('p3', p3);

    const p4 = MyPromise.resolve(MyPromise.resolve('Oh yeah'))
    console.log('p4', p4);

    const p5 = MyPromise.reject('Error Test')
    const p6 = MyPromise.reject(new MyPromise((resolve, reject) => {
      setTimeout(() => {
        resolve('OOOOkkkk')
      },1000)
    }))
    const p7 = MyPromise.reject(new Promise((resolve, reject) => {
      setTimeout(() => {
        reject('NNNNoooo')
      },5000)
    }))
    console.log('p5',p5,'p6',p6);

    const allTest = MyPromise.all([p2,p3,p4])
    console.log('allTest',allTest);

    const raceTest = MyPromise.race([p6, p7])
    console.log('raceTest', raceTest);

    // then异步执行
    const p1 = new MyPromise((resolve, reject) => {
      resolve('ok')
      console.log(1);
    })
    p1.then(value => {
      console.log(2);
    })
    console.log(3);
  </script>
</body>
</html>